package qier

import (
	"context"
	"errors"
	"fmt"
	_ "net/http/pprof"
	"strings"
	"time"

	"publish/pub-lib/utils"
	"github.com/astaxie/beego"
	"github.com/chromedp/cdproto/cdp"
	"github.com/lauyoume/chromedp"
)

var (
	QIER_VIDEO_CHROME_TIMEOUT = 900
)

func init() {
	QIER_VIDEO_CHROME_TIMEOUT = beego.AppConfig.DefaultInt("qier::video_chrome_timeout", 900)
	beego.Info("Qier Video Chrome Timeout", QIER_VIDEO_CHROME_TIMEOUT)
}

func PubVideo(ck string, cat string, videoPath string, imagePath string, title string, desc string, tag string) (err error) {
	beego.Info("下载视频中...")
	if err := utils.SaveFile(videoPath, "video.mp4"); err != nil {
		return err
	}
	beego.Info("下载视频 完成")
	defer utils.DeleteFile("./video.mp4")
	if err := utils.SaveFile(imagePath, "cover.png"); err != nil {
		return err
	}
	beego.Info("下载封面图 完成")
	defer utils.DeleteFile("./cover.png")

	cdp, err := utils.NewPubChrome()
	if err != nil {
		beego.Error("chrome 启动失败,error :", err)
		return err
	}
	defer utils.Close(cdp)

	cat, _ = CatNameToVideoName(cat)
	if cat == "" {
		cat = "其他-绝活"
	}

	duration := time.Second * time.Duration(QIER_VIDEO_CHROME_TIMEOUT)
	ctx, cancel := context.WithTimeout(context.Background(), duration)
	defer cancel()

	err = cdp.Run(ctx, pubVideo(ck, cat, "/video.mp4", "/cover.png", title, desc, tag))

	if err == utils.ErrFoundClass {
		return errors.New("当日已发满")
	}

	return err

	// timeout := time.After(time.Second * time.Duration(QIER_VIDEO_CHROME_TIMEOUT))
	// taskEnd := make(chan error)
	// go func() {
	// 	defer func() {
	// 		if r := recover(); r != nil {
	// 			taskEnd <- errors.New("发送未知错误【recover】")
	// 			beego.Error("[recover]", r)
	// 		}
	// 	}()
	// 	taskEnd <- utils.Run(cdp, pubVideo(ck, cat, "/video.mp4", "/cover.png", title, desc, tag))
	// }()

	// select {
	// case <-timeout:
	// 	beego.Warning("任务执行超时")
	// 	if err == nil {
	// 		err = errors.New("发布超时")
	// 	}
	// case err = <-taskEnd:
	// 	beego.Info("任务执行结束")
	// }

	// return err
}

func pubVideo(ck string, cat string, path string, imagePath string, title string, desc string, tag string) chromedp.Tasks {
	res := []byte{}
	catjs := fmt.Sprintf(`$('select').val('%s').trigger('chosen:updated')`, cat)
	tagAction := chromedp.Evaluate(`$('.titleVideoTags li a:eq(0), .titleVideoTags li a:eq(1), .titleVideoTags li a:eq(2), .titleVideoTags li a:eq(3), .titleVideoTags li a:eq(4)').click()`, &res)
	if tag != "" {
		tags := strings.Split(strings.Trim(tag, ","), ",")
		if len(tags) > 9 {
			tags = tags[:9]
		}
		if len(tags) > 1 {
			tag = strings.Join(tags, "\n") + "\n"
			tagAction = chromedp.SendKeys(`div[class="tagsinput"] > div > input`, tag, chromedp.NodeVisible)
		}
	}

	return chromedp.Tasks{
		utils.ActionCookies(`om.qq.com`, ck),
		// chromedp.Navigate(`https://om.qq.com/article/articlePublish#/!/view:article?typeName=multivideos`),
		chromedp.Navigate(`https://om.qq.com/article/articlePublish`),
		utils.MustNotClass(`button[action="publish"]`, "btn-disable", chromedp.ByQuery),
		chromedp.Click(`.mod-tab li[data-id="multivideos"]`, chromedp.ByQuery),
		chromedp.WaitVisible("#btn-upload-video", chromedp.ByID),
		chromedp.SendKeys(`input[name="Filedata"]`, utils.AbsolutePath(path), chromedp.NodeVisible),
		// chromedp.WaitVisible(`.form-video-cover`, chromedp.ByQuery),
		utils.WaitStyleMatch(`#om-art-videos-upload .bar`, "100%;", chromedp.ByQuery),
		chromedp.SetValue(`input[class="input-text"]`, "", chromedp.NodeVisible),
		chromedp.SendKeys(`input[class="input-text"]`, title, chromedp.NodeVisible),
		chromedp.SetValue(`textarea[class="textarea"]`, desc, chromedp.NodeVisible),
		chromedp.Evaluate(catjs, &res),
		chromedp.WaitVisible(`.titleVideoTags li a`, chromedp.ByQuery),
		tagAction,
		chromedp.Click(`button.action-cover`, chromedp.ByQuery),
		Println("wait button click"),
		// utils.Screenshot("body", "body.png", chromedp.ByQuery),
		// chromedp.WaitVisible(`.video-select-group`, chromedp.ByQuery),
		// Println("wait video popbody"),
		chromedp.WaitReady(`.video-select-group`, chromedp.ByQuery),
		//chromedp.WaitVisible(`.video-select-group`, chromedp.ByQuery),
		Println("wait video select ready"),
		chromedp.Click(`.video-select-group .tab li[data-id="crop"]`, chromedp.ByQuery),
		chromedp.SendKeys(`input[name="file"]`, utils.AbsolutePath(imagePath), chromedp.NodeVisible),
		chromedp.WaitVisible(`.jcrop-holder`, chromedp.ByQuery),
		Println("wait jcrop"),
		chromedp.Click(`.pop-action button.btn-primary`, chromedp.ByQuery),
		chromedp.Sleep(time.Second * 2),
		chromedp.Click(`button[action="publish"]`, chromedp.ByQuery),
		chromedp.Sleep(time.Second * 5),
	}
}

func Println(text string) chromedp.Action {
	return chromedp.ActionFunc(func(ctxt context.Context, h cdp.Executor) error {
		beego.Info("调试输出", text)
		return nil
	})
}
